<template>
    <div class="app-container">
        <div class="head">
            <img src="@/assets/img/Layout/position.png" />
            <p class="see-block">{{ titleType == 2 ? '其他出库单详情' : '其他出库单新建' }}</p>
        </div>
        <div class="view-container">
            <el-row class="status-title">
                <el-col class="mr20 width100" v-if="form.status == '0'">
                    <el-button
                        class="btn-success width100"
                        type="primary"
                        @click="submitForm()"
                    >确定</el-button>
                </el-col>
            </el-row>
            <el-form ref="form" :model="form" label-width="100px" class="mt30">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="单据编码:" prop="code">
                            <el-input v-model="form.code" placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="业务日期:" prop="businessDate">
                            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form.businessDate" suffix-icon="el-icon-date" type="datetime" placeholder="" style="width:100%;" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="form.status == '0' && form.contact !== '' && form.contact !== null">
                        <ul class="scan" style="width:60%;">
                            <li v-for="(item, index) in scanList" :key="index" @click="changeScan(index)" :class="{'active' : index == current }">{{ item }}</li>
                        </ul>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="业务部门:" prop="businessUnit">
                            <el-select v-model="form.businessUnit" style="width:100%;" placeholder="请选择" @change="onChangeSave" :disabled="form.status !== '0'">
                                <el-option
                                    v-for="item in businessUnitList"
                                    :key="item.value"
                                    :label="item.value"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="业务类型:" prop="businessType">
                            <el-select v-model="form.businessType" style="width:100%;" placeholder="请选择" @change="onChangeSave" :disabled="form.status !== '0'">
                                <el-option label="其他杂项出库" value="0"></el-option>
                                <el-option label="盘亏单" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="联系人:" prop="contact">
                            <el-input v-model="form.contact" placeholder="" @blur="onBlurSave" :disabled="form.status !== '0'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系号码:" prop="phone">
                            <el-input v-model="form.phone" placeholder="" @blur="onBlurSave" :disabled="form.status !== '0'" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="16">
                        <el-form-item label="联系地址:" prop="address">
                            <el-input v-model="form.address" placeholder="" @blur="onBlurSave" :disabled="form.status !== '0'" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="出库人:" prop="picker">
                            <el-input v-model="form.picker" placeholder="" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="form.remark" placeholder="" @blur="onBlurSave" :disabled="form.status !== '0'" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- class="input-data" -->
                <input v-model="code"
                    ref="getFocus"
                    class="input-data"
                    type="password"
                    @blur="onBlur()"
                    @keydown.enter="numberEnterDown()"
                    @keyup.enter="numberEnterUp()"
                />
            </el-form>
            <el-row class="detail-item">
                <el-col :span="24">
                    <el-table :data="productData">
                        <el-table-column label="序号" type="index" align="center" width="50" />
                        <el-table-column :label="item.label" :prop="item.prop" :width="item.width" v-for="(item, index) in columns" :key="index" align="center">
                            <template slot-scope="scope">
                                <template v-if="item.type == '1'">
                                    <el-input v-model="scope.row[item.prop]" placeholder="请输入" disabled="">
                                        <el-button slot="append" icon="el-icon-search" @click="productShow"></el-button>
                                    </el-input>
                                </template>
                                <template v-if="item.type == '3'">
                                    {{ scope.row[item.prop] }}
                                </template>
                                <template v-if="item.type == 'num'">
                                    <template v-if="form.status == '0'">
                                        <template v-if="scope.row.scanCode == '1' || scope.row.isSerial !== '0'">
                                            <el-input placeholder="请输入" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row)" :disabled="scope.row.multiPositionList !== null || form.status !== '0'" />
                                        </template>
                                        <template v-else>
                                            <el-input placeholder="请扫码" v-model="scope.row[item.prop]" disabled />
                                        </template>
                                    </template>
                                    <template v-else>
                                        {{ scope.row[item.prop] }}
                                    </template>
                                </template>
                                <template v-if="item.type == 'warehouse'">
                                    <el-select v-model="scope.row[item.prop]" placeholder="" style="width:100%;" disabled>
                                        <el-option v-for="(item,index) of warehouseList" :key="index" :label="item.name" :value="item.warehouseId"></el-option>
                                    </el-select>
                                </template>
                                <template v-if="item.type == 'remark'">
                                    <el-input placeholder="备注" v-model="scope.row[item.prop]" @blur="onBlurDataSave(scope.row)" :disabled="scope.row.productCode == '' || form.status !== '0'" />
                                </template>
                                <template v-if="item.type == 'del'">
                                    <span class="del" v-if="form.status == '0' && scope.row.endNum == 0" @click="deleteRow(scope.row)">删除</span>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
        </div>
        <!-- 弹出数据 -->
        <el-dialog :title="title" :visible.sync="open" width="80%" top="50px" append-to-body center :before-close="handleClose">
            <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
                <el-form-item :label="label" prop="searchValue">
                    <el-input
                    style="width:250px;"
                    v-model="queryParams.searchValue"
                    placeholder="请输入名称、编码、批次检索"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="list-search">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="loading" :data="dataList" @row-click="onSelectData" :default-sort="{prop: 'date', order: 'descending'}" border>
                <el-table-column label="序号" type="index" align="center" width="50">
                    <template slot-scope="scope">
                        <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
                <el-table-column label="SKU编码" align="center" prop="specificationCode" :show-overflow-tooltip="true" sortable />
                <el-table-column label="SKU名称" align="center" prop="specificationName" :show-overflow-tooltip="true" />
                <el-table-column label="规格" align="center" :show-overflow-tooltip="true" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.value1 == '' || scope.row.value1 == null ? '' : scope.row.value1 + scope.row.value2 }}
                    </template>
                </el-table-column>
                <el-table-column label="批次" align="center" prop="batchNumber" :show-overflow-tooltip="true" width="150" />
                <el-table-column label="库存" align="center" prop="storeNumber" :show-overflow-tooltip="true" width="100" />
                <el-table-column label="仓库" align="center" prop="warehouseName" :show-overflow-tooltip="true" width="100" />
                <el-table-column label="单位" align="center" prop="unit" :show-overflow-tooltip="true" />
                <el-table-column label="是否启用扫码" align="center" prop="isSerial" width="100">
                    <template slot-scope="scope">
                    <div v-if="scope.row.isSerial == '0'" style="color:#13C2C2">启用</div>
                    <div v-if="scope.row.isSerial == '1'" style="color:#52C41A">禁用</div>
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </el-dialog>
    </div>
</template>

<script>
import { otherOutboundAdd, otherOutboundDataAdd, otherOutboundEdit, otherOutboundDataEdit, otherOutboundDetail, otherOutboundDelete, morePosition, morePositionAdd, morePositionEdit, scanCode, confirmOutbound, getStock } from "@/api/system/warehouse/otherOutbound"
import { queryWarehouse } from "@/api/system/warehouse/warehouse"
import { listProduct} from "@/api/system/basicdata/basicdata"
import { listSalesProduct } from "@/api/system/basicdata/basicdata"
export default {
    name: "add",
    data() {
        return {
            id: '',
            form: {
                code: '', // 单据编码
                businessDate: '', // 业务日期
                businessUnit: '', // 业务部门
                businessType: '', // 业务类型
                // receivingWarehouse: '', // 接收仓库
                remark: '', // 备注
                picker: '', // 出库人
                // qualityInspectorName: '', // 质检员
                contact: '', // 联系人
                phone: '', // 联系电话
                address: '', // 联系地址
                detailList: [], // 产品数据
                status: '0',
            },
            scanList: ['扫码出库', '删除扫码'],
            code: '',
            current: 0, // 0 扫码出库 1 删除扫码
            // 部门列表
            businessUnitList: [{
                value: '采购部'
            },{
                value: '销售部'
            }],
            warehouseList: [], // 仓库列表
            titleType: 1, // 1 新建 2 查看
            // 产品数据
            searchProduct: [],
            // 表头
            columns: [{
                prop: "warehouse",
                label: "仓库",
                width: 130,
                type: 'warehouse'
            },{
                prop: "productCode",
                label: "sku编码",
                width: 200,
                type: '1'
            },{
                prop: "productName",
                label: "SKU名称",
                width: 250,
                type: '1'
            },{
                prop: "specification",
                label: "规格",
                width: 150,
                type: '3'
            },{
                prop: "batchNumber",
                label: "批次号",
                width: 150,
                type: '3'
            },{
                prop: "unit",
                label: "单位",
                width: 100,
                type: '3'
            },{
                prop: "endNum",
                label: "出库数量",
                width: 120,
                type: 'num'
            },{
                prop: "realTimeStock",
                label: "库存",
                width: 100,
                type: '3'
            },{
                prop: "remark",
                label: "备注",
                width: 200,
                type: 'remark'
            },{
                label: "",
                type: 'del',
                width: 80
            }],
            productData: [{
                productBasicId: '', // 产品ID
                productBasicCode: '', // 产品编码
                productBasicName: '', // 产品名称
                productId: '', // 物料id(SKU)
                productCode: '', // 物料编码(SKU)
                productName: '', // 物料名称(SKU)
                specification: '', // 规格
                batchNumber: '', // 批次号
                unit: '', // 单位
                endNum: '', // 出库数量
                warehouse: '', // 仓库
                areaId: '', // 区域id
                areaName: '', // 区域名称
                positionId: '', // 仓位id
                positionName: '', // 仓位名称
                enableBatches: '', // 是否启用批次
                isSerial: '', // 是否启用扫码
                remark: ''
            }],
            dataList:[],
            open: false,
            title: '',
            label: '',
            loading: true,
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                searchValue: undefined,
            },
        }
    },
    created(){
        // 获取用户信息
        let userInfo = this.$store.state.user.users
        this.form.picker = userInfo.userName
        if(this.$route.query.id){
            this.id = this.$route.query.id
            this.titleType = 2
            this.getDetailData()
        }
        this.getWarehouseList()
    },
    mounted(){
        if(this.form.status == '0'){
            this.$refs.getFocus.focus()
        }
    },
    methods: {
        // 获取详情
        getDetailData(){
            otherOutboundDetail(this.id).then(res => {
                this.form = res.data
                if(res.data.detailList == null){
                    this.productData = []
                }else{
                    this.productData = res.data.detailList
                    res.data.detailList.forEach(item => {
                        if(item.endNum == 0 || item.endNum == null){
                            item.endNum = ''
                        }
                    })
                }
                if(res.data.status == '0'){
                    this.addProduct()
                }
            })
        },
        // 获取仓库列表
        getWarehouseList(){
            queryWarehouse().then(res => {
                if(res.code == 200){
                    this.warehouseList = res.data
                }
            })
        },
        // 产品数据显示
        productShow(){
            if(this.form.status == '0'){
                if(this.form.contact !== '' && this.form.contact !== null){
                    this.open = true
                    this.title = '产品'
                    this.label = '搜索'
                    this.dataList = []
                    this.getList()
                }else{
                    this.$modal.msgError('联系人不能为空！')
                }
            }
        },
        // 获取弹窗数据
        getList(){
            this.loading = true
            listSalesProduct(this.addDateRange(this.queryParams)).then(res => {
                this.dataList = res.rows
                this.total = res.total
                this.loading = false
            })
        },
        // 搜索按钮
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        // 重置按钮
        resetQuery() {
            this.queryParams.searchValue = ''
            this.handleQuery()
        },
        // 选中数据
        onSelectData(row){
            // 产品选择
            let obj = ''
            obj = {
                otherInboundOrderId: this.id,
                productBasicId: row.productId, // 产品Id
                productBasicCode: row.productCode, // 产品编码
                productBasicName: row.productName, // 产品名称
                productId: row.specificationId, // sku产品Id
                productCode: row.specificationCode, // sku产品编码
                productName: row.specificationName, // sku产品名称
                batchNumber: row.batchNumber, // 批号
                specification: row.value1 + row.value2, // 规格
                unit: row.unit, // 单位
                enableBatches: row.enableBatches, // 是否启用批次
                scanCode: row.isSerial, // 是否启用批次
                warehouse: row.warehouseId, // 仓库
                areaId: row.areaId,
                positionId: row.positionId,
                remark: '', // 备注
            }
            // 判断编码是否重复
            let arr = this.productData.filter(item => item.productCode !== '')
            console.log(arr)
            if(arr && arr.length > 0){
                let index = this.productData.findIndex(item => item.productCode == row.specificationCode && item.batchNumber == row.batchNumber && item.warehouse == row.warehouseId)
                if(index > -1){
                    this.$modal.msgError('产品已存在，请重新选择！')
                    this.getDetailData()
                }else{
                    this.getOtherOutboundDataAdd(obj)
                }
                // this.getOtherOutboundDataEdit(obj)
            }else{
                this.getOtherOutboundDataAdd(obj)
            }
            this.open = false
            this.title = ''
            this.label = ''
            this.queryParams.searchValue = undefined
            this.handleQuery()
            this.dataList = []
        },
        // 关闭弹窗
        handleClose(){
            this.open = false
            this.title = ''
            this.label = ''
            this.queryParams.searchValue = undefined
            this.handleQuery()
            this.dataList = []
        },
        // 数量验证
        inputNum(val, row){
            // console.log(row)
            
        },
        // 扫码
        numberEnterDown() {
            this.keyDownTime = new Date().getTime()
        },
        numberEnterUp() {
            this.keyUpTime = new Date().getTime()
            if (this.keyUpTime - this.keyDownTime < 30) {
                // 扫码枪触发
                let newCode = this.common.codeRule(this.code)
                if(this.id){
                    if(newCode.length == 13 || newCode.length == 20){
                        if(this.current == 0){
                            // 扫码出库
                            scanCode(this.id, newCode).then(res => {
                                if(res.code == 200){
                                    this.code = ''
                                    this.getDetailData()
                                }else{
                                    this.code = ''
                                    this.$modal.msgError(res.msg)
                                }
                            })
                        }else{
                            // 删除扫码
                            otherOutboundDelete({otherInboundOrderId: this.id, code: newCode}).then(res => {
                                if(res.code == 200){
                                    this.code = ''
                                    this.getDetailData()
                                }else{
                                    this.code = ''
                                    this.$modal.msgError(res.msg)
                                }
                            })
                        }
                    }else{
                        this.code = ''
                        this.$refs.getFocus.focus()
                        this.$modal.msgError('扫码错误，请重新扫码!')
                    }
                }else{
                    otherOutboundAdd(this.form).then(res=> {
                        if(res.code == 200){
                            this.id = res.data.id
                            if(newCode.length == 13 || newCode.length == 20){
                                // 扫码出库
                                console.log(this.id)
                                scanCode(this.id, newCode).then(res => {
                                    if(res.code == 200){
                                        this.code = ''
                                        this.getDetailData()
                                    }else{
                                        this.code = ''
                                        this.$modal.msgError(res.msg)
                                    }
                                })
                            }else{
                                this.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgError('扫码错误，请重新扫码!')
                            }
                        }
                    })
                }
            }else{
                // 直接按键盘触发
                let newCode = this.common.codeRule(this.code)
                if(this.id){
                    if(newCode.length == 13 || newCode.length == 20){
                        if(this.current == 0){
                            // 扫码出库
                            this.$modal.loading("正在加载")
                            scanCode(this.id, newCode).then(res => {
                                if(res.code == 200){
                                    this.code = ''
                                    this.getDetailData()
                                    this.$modal.closeLoading()
                                }else{
                                    this.code = ''
                                    this.$modal.msgError(res.msg)
                                    this.$modal.closeLoading()
                                }
                            })
                        }else{
                            // 删除扫码
                            this.$modal.loading("正在加载")
                            otherOutboundDelete({otherInboundOrderId: this.id, code: newCode}).then(res => {
                                if(res.code == 200){
                                    this.code = ''
                                    this.getDetailData()
                                    this.$modal.closeLoading()
                                }else{
                                    this.code = ''
                                    this.$modal.msgError(res.msg)
                                    this.$modal.closeLoading()
                                }
                            })
                        }
                    }else{
                        this.code = ''
                        this.$refs.getFocus.focus()
                        this.$modal.msgError('扫码错误，请重新扫码!')
                    }
                }else{
                    otherOutboundAdd(this.form).then(res=> {
                        if(res.code == 200){
                            this.id = res.data.id
                            if(newCode.length == 13 || newCode.length == 20){
                                // 扫码出库
                                // console.log(this.id)
                                this.$modal.loading("正在加载")
                                scanCode(this.id, newCode).then(res => {
                                    if(res.code == 200){
                                        this.code = ''
                                        this.getDetailData()
                                        this.$modal.closeLoading()
                                    }else{
                                        this.code = ''
                                        this.$modal.msgError(res.msg)
                                        this.$modal.closeLoading()
                                    }
                                })
                            }else{
                                this.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgError('扫码错误，请重新扫码!')
                            }
                        }
                    })
                }
            }
        },
        // 切换扫码出库/删除扫码
        changeScan(index){
            this.current = index
            this.code = ''
            if(index == 1){
                this.$modal.msgError("删除扫码")
            }else{
                this.$modal.msgSuccess("扫码出库")
            }
            this.$refs.getFocus.focus()
        },
        onBlur(){
            this.current = -1
            if(this.id == ''){
                this.getOtherInboundOrderAdd()
            }
        },
        // 添加一条产品信息
        addProduct(){
            let data = {
                key: {
                    otherInboundOrderId: this.id ? this.id : '',
                    productId: ''
                }
            }
            this.columns.forEach(item =>{
                data.key[item.prop] = ''
            })
            this.productData.push(JSON.parse(JSON.stringify(data.key)))
        },
        // 删除产品数据
        deleteRow(item){
            if(item.status == '0'){
                if(item.productId !== ''){
                    this.$modal.confirm('是否确认删除当前数据？', '删除').then(() => {
                        otherOutboundDelete({otherOutId: item.id}).then(res => {
                            if(res.code == 200){
                                this.getDetailData()
                            }
                        })
                    }).catch(() => {})
                }else{
                    this.$modal.msgError('最少保留一条可编辑数据！')
                }
            }
        },
        // 保存出库单数据
        onChangeSave(){
            this.getOtherInboundOrderAdd()
        },
        onBlurSave(){
            this.getOtherInboundOrderAdd()
        },
        onBlurDataSave(row){
            // 编辑产品数据
            otherOutboundDataEdit(row).then(res=> {
                if(res.code == 200){
                    this.getDetailData()
                    this.$modal.msgSuccess("操作成功")
                }
            })
        },
        // 新建出库单数据
        getOtherInboundOrderAdd(){
            let data = this.productData.filter(item => item.productCode !== '')
            this.form.detailList = data
            if(this.id){
                let arr = this.form
                arr.id = this.id
                otherOutboundEdit(arr).then(res => {
                    if(res.code == 200){
                        this.getDetailData()
                        // this.$modal.msgSuccess("操作成功")
                    }
                })
            }else{
                // 新建
                otherOutboundAdd(this.form).then(res=> {
                    if(res.code == 200){
                        this.id = res.data.id
                        this.getDetailData()
                        // this.$modal.msgSuccess("操作成功")
                    }
                })
            }
        },
        // 新建产品数据
        getOtherOutboundDataAdd(row){
            otherOutboundDataAdd(row).then(res=> {
                if(res.code == 200){
                    this.getDetailData()
                    this.$modal.msgSuccess("操作成功")
                }
            })
        },
        // 编辑产品数据
        getOtherOutboundDataEdit(row){
            otherOutboundDataEdit(row).then(res=> {
                if(res.code == 200){
                    this.getDetailData()
                    this.$modal.msgSuccess("操作成功")
                }
            })
        },
        submitForm(){
            // 过滤掉空数据
            let arr = this.productData.filter(item => item.productCode !== '')
            this.form.detailList = arr
            let endNum = this.form.detailList.every(val => !!val.endNum)
            if(endNum == true){
                this.$modal.loading("正在提交")
                confirmOutbound(this.id).then(res => {
                    if(res.code == 200){
                        this.$modal.msgSuccess("操作成功")
                        this.$tab.closeOpenPage({ path: "/warehouseManagement/warehouse/otherOutbound" })
                        this.$modal.closeLoading()
                    }
                })
            }else{
                this.$modal.msgError('出库数量不能为空！')
            }
        }
    }
}
</script>

<style scoped>
::v-deep .el-input .el-input-group__append{
  padding: 0 10px;
}
.del{
  color: #ff0000;
  cursor: pointer;
}
.more{
  font-size: 30px;
  cursor: pointer;
}
::v-deep .el-dialog__header{
  display: none;
}
.icon-more-position{
  font-size: 22px;
  margin: 0 5px;
  cursor: pointer;
}
</style>